<?php

namespace app\v1\controller;

use support\Request;
use app\model\CartModel;
use app\model\GoodsModel;
use app\model\GoodsKuModel;
use app\model\OrderModel;
use app\model\OrderItemModel;
use Exception;
use support\Db;
use support\Log;

/**
 * 购物车控制器
 * 
 * @package app\v1\controller
 */
class CartController
{
    /**
     * 添加到购物车
     * 
     * @param Request $request
     * @return mixed
     */
    public function add(Request $request)
    {
        try {
            // 参数验证
            $goodsId = $request->post('goods_id');
            $sku_id = $request->post('sku_id');
            $quantity = $request->post('quantity', 1);
            $user = $request->userLogin;

            if (empty($goodsId)) {
                throw new Exception('商品ID不能为空');
            }


            if ($quantity <= 0) {
                throw new Exception('商品数量必须大于0');
            }

            // 验证商品是否存在
            $goods = GoodsModel::find($goodsId);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            // 验证规格是否存在
            $sku = GoodsKuModel::find($sku_id);
            if (!$sku) {
                throw new Exception('商品规格不存在');
            }

            // 检查库存
            if ($sku->v < $quantity) {
                throw new Exception('商品库存不足');
            }

            // 检查购物车是否已存在相同商品和规格
            $existingCart = CartModel::where('user_id', $user->id)
                ->where('goods_id', $sku_id)
                ->first();

            if ($existingCart) {
                // 更新数量
                $newQuantity = $existingCart->quantity + $quantity;
                if ($sku->v < $newQuantity) {
                    throw new Exception('商品库存不足');
                }
                
                $existingCart->update([
                    'quantity' => $newQuantity,
                    'updated_at' => time()
                ]);
                
                $cartId = $existingCart->id;
            } else {
                // 新增购物车记录
                $cart = CartModel::create([
                    'user_id' => $user->id,
                    'goods_id' => $goodsId,
                    'sku_id' => $sku_id,
                    'quantity' => $quantity,
                    'created_at' => time(),
                    'updated_at' => time()
                ]);
                
                $cartId = $cart->id;
            }

            return json([
                'data' => [
                    'cart_id' => $cartId,
                    'message' => '添加到购物车成功'
                ],
                'msg' => '添加到购物车成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取购物车列表
     * 
     * @param Request $request
     * @return mixed
     */
    public function list(Request $request)
    {
        try {
            $user = $request->userLogin;

            // 获取购物车列表
            $cartList = CartModel::select([
                    'cart.id as cart_id',
                    'cart.quantity',
                    'cart.created_at',
                    'cart.sku_id',
                    'goods.id as goods_id',
                    'goods.name as goods_name',
                    'goods.image as goods_image',
                    'goods_ku.price as sku_price',
                    'goods_ku.v as sku_stock',
                    'goods_ku.specs as sku_specs'
                ])
                ->join('goods', 'cart.goods_id', '=', 'goods.id')
                ->join('goods_ku', 'cart.sku_id', '=', 'goods_ku.id')
                ->where('cart.user_id', '=',$user->id)
                ->get();

            // 计算总价和总数量
            $totalPrice = 0;
            $totalQuantity = 0;
            foreach ($cartList as $item) {
                $itemPrice = $item['sku_price'] ?: $item['goods_price'];
                $totalPrice += $itemPrice * $item['quantity'];
                $totalQuantity += $item['quantity'];

                $item['sku_price'] = round($item['sku_price'], 2);
            }

            $result = [
                'list' => $cartList,
                'total_price' => $totalPrice,
                'total_quantity' => $totalQuantity,
                'count' => count($cartList)
            ];

            return json([
                'data' => $result,
                'msg' => '获取购物车列表成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 更新购物车商品数量
     * 
     * @param Request $request
     * @return mixed
     */
    public function updateQuantity(Request $request)
    {
        try {
            $cartId = $request->post('cart_id');
            $quantity = $request->post('quantity');
            
            if (empty($cartId)) {
                throw new Exception('购物车记录ID不能为空');
            }
            
            if ($quantity <= 0) {
                throw new Exception('商品数量必须大于0');
            }

            // 查找购物车记录
            $cart = CartModel::find($cartId);
            if (!$cart) {
                throw new Exception('购物车记录不存在');
            }

            // 验证库存
            $sku = GoodsKuModel::where('goods_id', $cart->goods_id)
                ->where('specs', $cart->spec)
                ->first();
            
            if (!$sku || $sku->stock < $quantity) {
                throw new Exception('商品库存不足');
            }

            // 更新数量
            $cart->update([
                'quantity' => $quantity,
                'updated_at' => time()
            ]);

            return json([
                'data' => [
                    'cart_id' => $cartId,
                    'quantity' => $quantity,
                    'message' => '更新数量成功'
                ],
                'msg' => '更新数量成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除购物车商品
     * 
     * @param Request $request
     * @return mixed
     */
    public function remove(Request $request)
    {
        try {
            $cartId = $request->post('cart_id');
            
            if (empty($cartId)) {
                throw new Exception('购物车记录ID不能为空');
            }

            // 查找并删除购物车记录
            $cart = CartModel::find($cartId);
            if (!$cart) {
                throw new Exception('购物车记录不存在');
            }

            $cart->delete();

            return json([
                'data' => [
                    'cart_id' => $cartId,
                    'message' => '删除成功'
                ],
                'msg' => '删除成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 清空购物车
     * 
     * @param Request $request
     * @return mixed
     */
    public function clear(Request $request)
    {
        try {
            $userId = $request->post('user_id');
            
            if (empty($userId)) {
                throw new Exception('用户ID不能为空');
            }

            // 删除用户的所有购物车记录
            $deletedCount = CartModel::where('user_id', $userId)->delete();

            return json([
                'data' => [
                    'deleted_count' => $deletedCount,
                    'message' => '清空购物车成功'
                ],
                'msg' => '清空购物车成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取购物车商品总数
     * 
     * @param Request $request
     * @return mixed
     */
    public function count(Request $request)
    {
        try {
            $userId = $request->get('user_id');
            
            if (empty($userId)) {
                throw new Exception('用户ID不能为空');
            }

            // 获取购物车商品总数
            $count = CartModel::where('user_id', $userId)->count();

            return json([
                'data' => [
                    'count' => $count
                ],
                'msg' => '获取购物车商品总数成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function submit(Request $request)
    {
        try {
            $user = $request->userLogin;
            $input = $request->post();

            $expressType = $input['expressType'] ?? null;
            $address = $input['address'] ?? [];

            if(empty($address)){
                throw new Exception('需要选择地址信息');
            }

            if(in_array($expressType,['pickUpPoint','express']) === false){
                throw new Exception('请选择配送方式');
            }

            if($expressType == 'pickUpPoint'){
                $pickUpPoint = $input['pickUpPoint'] ?? [];
                if(empty($pickUpPoint)){
                    throw new Exception('请选择取货点');
                }
            }

            $items = $input['items'] ?? [];
            if(empty($items)){
                throw new Exception(message: '请选择要购买的商品');
            }

            $totalQuantity = 0;// 总数量
            $totalMoney = 0;// 总金额
            $payTotalAmount = 0;
            $discountTotalAmount = 0;


            Db::beginTransaction();

            try {
                $order = new OrderModel();
                $order->user_id = $user->id;
                $order->total_amount = $totalMoney;
                $order->pay_amount = $payTotalAmount;
                $order->discount_amount = $discountTotalAmount;
                $order->status = 0;
                $order->pay_status = 0;
                $order->pay_time = 0;
                $order->created_at = time();
                $order->updated_at = time();
                $order->sender_phone = $user->phone;
    
                $order->express_type = $expressType;
                if($expressType == 'pickUpPoint'){
                    $order->pick_up_point_id = $pickUpPoint['id'];
                }
    
                $order->address_id = $address['id'];
                $order->delivery_status = 0;
                $order->receiver_name = $address['name'];
                $order->receiver_phone = $address['phone'];
                $order->receiver_province = $address['province'];
                $order->receiver_city = $address['city'];
                $order->receiver_district = $address['district'];
                $order->receiver_address = $address['detail'];
                $order->save();
    
                foreach($items as $item){
                    $cart = CartModel::find($item['cart_id']);
                    $goods = GoodsModel::find($cart->goods_id);
                    $ku = GoodsKuModel::find($cart->sku_id);
    
                    $vipDiscount = $goods->vip_discount;
                    $amount =  $ku->price * $cart->quantity;
    
                    $pay_amount = 0;
                    $discount_amount = 0;
    
                    if($vipDiscount > 0 && $user->isVip() && $vipDiscount < 100){
                        // 有折扣
                        $pay_amount = round(($amount * ($vipDiscount / 100)),2);
                        $discount_amount = round(($amount - $pay_amount),2);
                    }else{
                        // 无折扣
                        $pay_amount = $amount;
                        $discount_amount = 0;
                    }
    
                    $totalQuantity += $cart->quantity;
                    $totalMoney += $amount;
                    $payTotalAmount += $pay_amount;
                    $discountTotalAmount += $discount_amount;

                    $cart->delete();
                }
    
                // 四舍五入
                $totalMoney = round($totalMoney,2);
                $payTotalAmount = round($payTotalAmount,2);
                $discountTotalAmount = round($discountTotalAmount,2);
    
    
                // update order
                $order->total_amount = $totalMoney;
                $order->pay_amount = $payTotalAmount;
                $order->discount_amount = $discountTotalAmount;
                
                $order->save();
    
    
                foreach($items as $item){
                    $ku = GoodsKuModel::find($item['sku_id']);
    
                    $oi = new OrderItemModel();
                    $oi->order_id = $order->id;
                    $oi->goods_id = $item['goods_id'];
                    $oi->goods_ku_id = $item['sku_id'];
                    $oi->goods_title = $item['goods_name'];
                    $oi->goods_image = $item['goods_image'];
    
                    // $oi->sku_specs = json_encode($input['specs']);
                    $oi->sku_spec_names = json_encode(explode('@',$ku->specs),256);
    
                    $oi->unit_price = $ku->price;
                    $oi->quantity = $item['quantity'];
                    $oi->total_price = $ku->price * $item['quantity'];
                    $oi->discount_amount = $discount_amount;
                    $oi->final_price = $pay_amount;
                    $oi->final_price = $pay_amount;
                    $oi->created_at = time();
                    $oi->updated_at = time();
                    $oi->user_id = $user->id;
                    $oi->save();
                }

                Db::commit();

                return json([
                    'data' => [
                        'order_id' => $order->id,
                        'total_amount' => $amount,
                    ],
                    'msg' => '提交订单成功',
                    'code' => 1
                ]);
            } catch (Exception $e) {
                Db::rollBack();
                throw $e;
            }
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
}
